package com.my.oschina.adapter;

import java.util.ArrayList;
import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;

import com.my.oschina.MainActivity;
import com.my.oschina.bean.PostList;
import com.my.oschina.common.AppFragmentPagerAdapter;
import com.my.oschina.fragment.QuestionFragment;

/**
 * 问答-PagerAdaper，继承了AppFragmentPagerAdapter，后者又继承了PagerAdapter
 */
public class QuestionFragmentPagerAdapter extends AppFragmentPagerAdapter {

	private List<Fragment> fragmentList;
	private static int QUES_TAB_SIZE = 5;
	private String[] tagString = { "tag0", "tag1", "tag2", "tag3", "tag4" };

	public QuestionFragmentPagerAdapter(QuestionFragment qf,
			ViewPager viewPager, FragmentManager fm, MainActivity activity,
			List<Fragment> fragmentList) {
		super(fm);
		
		this.fragmentList = fragmentList;

		fragmentList.add(0, qf.getQuesChildFragment(PostList.CATALOG_ASK));
		fragmentList.add(1, qf.getQuesChildFragment(PostList.CATALOG_SHARE));
		fragmentList.add(2, qf.getQuesChildFragment(PostList.CATALOG_OTHER));
		fragmentList.add(3, qf.getQuesChildFragment(PostList.CATALOG_JOB));
		fragmentList.add(4, qf.getQuesChildFragment(PostList.CATALOG_SITE));

		FragmentTransaction ft = qf.getChildFragmentManager()
				.beginTransaction();

		for (int i = 0; i < QUES_TAB_SIZE; i++) {
			if (fragmentList.get(i).isAdded()) {
				ft.add(viewPager.getId(), fragmentList.get(i), tagString[i]);
			}
		}

		if (!ft.isEmpty()) {
			ft.commit();
			qf.getChildFragmentManager().executePendingTransactions();
		}
	}

	@Override
	public Fragment getItem(int position) {
		return fragmentList.get(position);
	}

	@Override
	protected String getTag(int position) {
		List<String> tagList = new ArrayList<String>();

		for (int i = 0; i < QUES_TAB_SIZE; i++) {
			tagList.add(tagString[i]);
		}

		return tagList.get(position);
	}

	@Override
	public int getCount() {
		return QUES_TAB_SIZE;
	}

}
